package com.mobilepoc.jersey.location;

import com.mobilepoc.jersey.model.Coordinates;

/**
 * This uses the ‘haversine’ formula to calculate the great-circle distance between two points – that is, the shortest
 * distance over the earth’s surface – giving an ‘as-the-crow-flies’ distance between the points (ignoring any hills, of
 * course!).
 * 
 * http://www.movable-type.co.uk/scripts/latlong.html
 * 
 * @author Nicklas Lundin
 */
public class DistanceCalculator {
    private static final int R = 6378; // km

    /**
     * Returns the distance between two {@link Coordinates}
     * 
     * @param l1 First {@link Coordinates}
     * @param l2 Second {@link Coordinates}
     * @return the distance (in km) between the two coordinates
     */
    public static double calculateDistance(Coordinates l1, Coordinates l2) {

        double dLat = Math.toRadians(l2.getLatitude() - l1.getLatitude());
        double dLon = Math.toRadians(l2.getLongitude() - l1.getLongitude());
        double lat1 = Math.toRadians(l1.getLatitude());
        double lat2 = Math.toRadians(l2.getLatitude());

        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1)
                * Math.cos(lat2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        double d = R * c;

        return d;
    }

}
